package com.example.algorithm.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author : zhy
 * @since : 2022/7/29
 */
public class PerForeach {


    /**--------------------------------广度遍历------------------------------------*/
    public List<Integer> preorderTraversal(TreeNode root){

        List<Integer> list=new ArrayList<>();
        if(root==null)
        {
            return list;
        }
        Stack<TreeNode> stack=new Stack<>();
        stack.push(root);
        while(!stack.isEmpty())
        {
            TreeNode node=stack.pop();
            list.add(node.val);
            if(node.right!=null){
                stack.push(node.right);
            }
            if(node.left!=null)
            {
                stack.push(node.left);
            }
        }
        return list;
    }

    /**--------------------------------深度遍历------------------------------------*/

    public List<Integer> preorderTraversal1(TreeNode root)
    {
        List<Integer> list=new ArrayList<>();
        if (root==null)
        {
            return list;
        }
        dfs(list,root);
        return list;
    }

    private void dfs(List<Integer> list, TreeNode root) {
        if(root==null){
            return;
        }
        list.add(root.val);
        dfs(list, root.left);
        dfs(list, root.right);
    }

}
